package com.kyxx.topics;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.kyxx.topics.activity.DetailAdvertiseActivity;
import com.kyxx.topics.activity.UserLoginActivity2;
import com.kyxx.topics.bean.AdBean;
import com.kyxx.topics.bean.AppBean;
import com.kyxx.topics.fragment.MainFragment2;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.ApkUpdateUtils;
import com.kyxx.topics.utils.Log;
import com.kyxx.topics.utils.NetworkUtils;
import com.kyxx.topics.utils.PreferenceUtil;
import com.kyxx.topics.utils.SettingUtils;
import com.kyxx.topics.utils.TimeUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.widget.NativeTabButton;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.pgyersdk.activity.FeedbackActivity;
import com.pgyersdk.feedback.PgyFeedbackShakeManager;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.uuch.adlibrary.AdConstant;
import com.uuch.adlibrary.AdManager;
import com.uuch.adlibrary.bean.AdInfo;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends BaseActivity2 {
    private List<AdInfo> advList;
    private NativeTabButton[] mTabButtons;
    private Fragment[] mFragments;
    private static LinearLayout ll_bottom_tab;
    private int title[] = {R.string.my_index1, R.string.my_index2,
            R.string.my_index3, R.string.my_index4};
    private int checkImage[] = {R.mipmap.home_selected, R.mipmap.zhibo_select,
            R.mipmap.vip_selected, R.mipmap.mine_selected};
    private int unCheckImage[] = {R.mipmap.home, R.mipmap.zhibo,
            R.mipmap.vip, R.mipmap.mine};
    private boolean isExit;
    SettingUtils settingUtils = new SettingUtils();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_main);
        ApkUpdateUtils.checkUpdate(MainActivity.this, true);
        initData();
        if (!NetworkUtils.isAvailable(context)) {
            ToastUtils.show(context, "网络错误请稍后再试");
        }
//        PgyUpdateManager.register(MainActivity.this, new UpdateManagerListener() {
//
//            @Override
//            public void onNoUpdateAvailable() {
//                Log.e("update", "no");
//            }
//
//            @Override
//            public void onUpdateAvailable(String s) {
//                Log.e("update", s);
//                final AppBean appBean = JSON.parseObject(s, AppBean.class);
//                new AlertDialog.Builder(MainActivity.this)
//                        .setTitle("更新")
//                        .setMessage("版本号：" + appBean.getData().getVersionName() + "\n" + appBean.getData().getReleaseNote())
//                        .setPositiveButton("取消", null)
//                        .setNegativeButton(
//                                "确定",
//                                new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(
//                                            DialogInterface dialog,
//                                            int which) {
//                                        startDownloadTask(
//                                                MainActivity.this,
//                                                appBean.getData().getDownloadURL());
//                                    }
//                                }).show();
//            }
//        });
        BaseApp.getInstance().addActivity(this);
        mFragments = new Fragment[4];
        mTabButtons = new NativeTabButton[4];
    }

    @Override
    protected void findViewById() {
        ll_bottom_tab = (LinearLayout) findViewById(R.id.ll_bottom_tab);
        mFragments[0] = getSupportFragmentManager().findFragmentById(
                R.id.fragment_home);
        mFragments[1] = getSupportFragmentManager().findFragmentById(
                R.id.fragment_coupon);
        mFragments[2] = getSupportFragmentManager().findFragmentById(
                R.id.fragment_shop);
        mFragments[3] = getSupportFragmentManager().findFragmentById(
                R.id.fragment_mine);
        mTabButtons[0] = (NativeTabButton) findViewById(R.id.tab_button_home);
        mTabButtons[1] = (NativeTabButton) findViewById(R.id.tab_button_coupon);
        mTabButtons[2] = (NativeTabButton) findViewById(R.id.tab_button_shop);
        mTabButtons[3] = (NativeTabButton) findViewById(R.id.tab_button_mine);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic() {
        for (int i = 0; i < 4; i++) {
            mTabButtons[i].setTitle(getString(title[i]));
            mTabButtons[i].setIndex(i);
            mTabButtons[i].setSelectedImage(getResources().getDrawable(
                    checkImage[i]));
            mTabButtons[i].setUnselectedImage(getResources().getDrawable(
                    unCheckImage[i]));
        }
        setFragmentShow(0);
    }

    public void setFragmentShow(int which) {
        if (which == 2 && TextUtils.isEmpty(BaseApp.getModel().getId())) {
            startActivity(UserLoginActivity2.class);
            return;
        }
        getSupportFragmentManager().beginTransaction().hide(mFragments[0])
                .hide(mFragments[1]).hide(mFragments[2]).hide(mFragments[3])
                .show(mFragments[which]).commit();
        mTabButtons[0].setSelectedButton(false);
        mTabButtons[1].setSelectedButton(false);
        mTabButtons[2].setSelectedButton(false);
        mTabButtons[3].setSelectedButton(false);
        mTabButtons[which].setSelectedButton(true);

    }

    public void replaceFragment0() {
        MainFragment2 mainFragment2 = new MainFragment2().newInstace(null);
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_home, mainFragment2).commit();
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        exit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtils.show(MainActivity.this, "再按一次退出程序");
            // 利用handler延迟发送更改状态信息
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            BaseApp.getInstance().exit();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(BaseApp.getModel().getId())) {
            if (settingUtils.isTuiSongTongZhi()) {
                JPushInterface.setAlias(context, BaseApp.getModel().getId(), new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                        android.util.Log.e("别名", BaseApp.getModel().getId());
                    }
                });
            } else {
                JPushInterface.setAlias(context, "1", new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                        android.util.Log.e("别名", "1");
                    }
                });
            }
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (PreferenceUtil.getString("adtime") == null || PreferenceUtil.getString("adtime").equals(TimeUtils.getStrTime_md(System.currentTimeMillis() + ""))) {
            return;
        }
        HttpParams params = new HttpParams();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("position", 4);
        params.put("json", jsonObject.toString());
        OkGoRequest.post(UrlUtils.getAlertAdv, MainActivity.this, "ad", CacheMode.REQUEST_FAILED_READ_CACHE, params, new LoadingStringCallBack(MainActivity.this, false) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    PreferenceUtil.putString("adtime", TimeUtils.getStrTime_md(System.currentTimeMillis() + ""));
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    advList = JSON.parseArray(result.getJSONArray("data").toString(), AdInfo.class);
                    if (advList == null || advList.size() == 0)
                        return;
                    for (int i = 0; i < advList.size(); i++) {
                        advList.get(i).setActivityImg(UrlUtils.BASEHTTP + advList.get(i).getActivityImg());
                    }
                    AdManager adManager = new AdManager(MainActivity.this, advList);
                    adManager.setOnImageClickListener(new AdManager.OnImageClickListener() {
                        @Override
                        public void onImageClick(View view, AdInfo advInfo) {
                            Intent intent = new Intent(context, DetailAdvertiseActivity.class);
                            intent.putExtra("title", advInfo.getTitle());
                            intent.putExtra("id", advInfo.getAdId());
                            startActivity(intent);
                        }
                    }).showAdDialog(AdConstant.ANIM_UP_TO_DOWN);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
//        advList = new ArrayList<>();
//        AdInfo adInfo = new AdInfo();
//        adInfo.setActivityImg("https://raw.githubusercontent.com/yipianfengye/android-adDialog/master/images/testImage1.png");
//        advList.add(adInfo);
//
//        adInfo = new AdInfo();
//        adInfo.setActivityImg("https://raw.githubusercontent.com/yipianfengye/android-adDialog/master/images/testImage2.png");
//        advList.add(adInfo);
    }
}
